package com.xdxc.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class HmacUtil {
    private static final String HMAC_ALGO = "HmacSHA256";

    /**
     * 使用 secret 对 data 签名，返回 Base64 编码字符串
     */
    public static String sign(String data, String secret) {
        try {
            Mac mac = Mac.getInstance(HMAC_ALGO);
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_ALGO));
            byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(rawHmac);
        } catch (Exception e) {
            throw new IllegalStateException("Failed to generate HMAC : " + e.getMessage(), e);
        }
    }

    /**
     * 校验签名是否匹配
     */
    public static boolean verify(String data, String secret, String signature) {
        String calculated = sign(data, secret);
        return calculated.equals(signature);
    }
}
